﻿using System.Threading.Tasks;

namespace KingerRobot.MexicoSailunMDC.Biz;
/// <summary>
/// Ems 小车入库口绑定任务
/// EMS取料
/// </summary>
public class EMSInputBiz : K8.MDCBB.Biz
{
    #region 配置参数
    private ParamData Param { get; set; }

    class ParamData
    {

        /// <summary>
        /// EMS 取胎位置ID
        /// </summary>
        public long EmsLocId { get; set; }
        /// <summary>
        /// 线体编号
        /// </summary>
        public string StationNo { get; set; }
        /// <summary>
        /// EMS 取胎位置名称
        /// </summary>
        public string EmsLocName { get; set; }
    }
    #endregion

    #region PLC 通讯参数
    private ValueData Data { get; set; }
    class ValueData
    {

        ///// <summary>
        ///// 产品条码
        ///// </summary>
        //public string ProductCode { get; set; }
        //下面是读取信息
        //任务号
        public int RWorkNo { get; set; }
        /// <summary>
        /// 有胎标识 1有胎
        /// </summary>
        public int tStatus { get; set; }

    }
    #endregion

    #region 缓存
    private CacheData Cache { get; set; }
    class CacheData
    {
        //任务号
        public int? TaskNo { get; set; }



        public DateTime catchDate { get; set; }

        public long locId { get; set; }
    }
    #endregion

    #region 实时日志
    private StepData Step { get; set; }
    class StepData
    {
        private string _msg = string.Empty;
        public string StepMsg
        {
            get
            {
                return this._msg;
            }
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    this._msg = string.Empty;
                    return;
                }

                this._msg = $"{System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}>>{value}";
            }
        }
    }
    private void StepMsg(string msg)
    {
        this.Step.StepMsg = msg;
        this.WriteLog(msg);
    }
    #endregion

    #region 文件日志（运行需要 Nlog 配置）
    private void WriteLog(string message)
    {
        K8.LSF.Client.Log(new K8.LSF.Log { Data = message });
    }
    #endregion

    /// <summary>
    /// 和 PLC 通讯对象
    /// </summary>
    private BizData BizData { get; set; }
    public int Execute(BizData writer)
    {
        // Excute 方法外使用 BizData
        this.BizData = writer;
        // 返回参数
        var result = 0;

        var taskNo = Data.RWorkNo;

        //var TStatus = Data.tStatus;
        ////如有没流水号 有胎 绑定异常胎信息
        //if (TStatus == 1)
        //{

        //    if (taskNo == 0)
        //    {


        //        this.StepMsg($"任务{taskNo},绑定异常胎信息120");
        //        try
        //        {
        //            var warehousingAfterService = K8.RSF.Client.Create<IExWarehousingAfterService>();
        //            var finishResult = warehousingAfterService.EmsInputEMSAbnormalTask(Param.EmsLocId);
        //            this.StepMsg($"任务{taskNo},绑定异常胎信息124,返回finishResult,{finishResult.ToJson()}");
        //        }
        //        catch (Exception ex)
        //        {
        //            this.StepMsg($"任务{taskNo},绑定异常胎信息错误,{ex.ToString()}");
        //        }
        //    }
        //}


        if (taskNo == 0)
        {
            this.StepMsg($"任务号为空.");
            return result;
        }
        this.StepMsg($"任务号{taskNo}开始执行绑定.");
        if (taskNo == Cache.TaskNo)
        {
            this.StepMsg($"任务{taskNo}已绑定位置{Param.EmsLocId}.");

            return result;
        }
        var taskService = K8.RSF.Client.Create<ITaskService>();
        var warehousingAfterService = K8.RSF.Client.Create<IExWarehousingAfterService>();
        this.StepMsg($"任务号{taskNo}开始执行绑定1111.");
        var taskbean = taskService.GetTaskBeanByTaskNo(taskNo);
        //如果查不到任务号 生成异常任务
        if (taskbean is null)
        {
            this.StepMsg($"任务号{taskNo}开始执行绑定 is null.");
            try
            {
                this.StepMsg($"任务号{taskNo}开始执行绑定222");
                var abnormalTask = taskService.GetEmsTaskBeanByTaskNo(taskNo, Param.EmsLocId);
                this.StepMsg($"任务号{taskNo}开始执行绑定333abnormalTask{abnormalTask.ToJson()}");
            }
            catch (Exception ex) 
            {
                this.StepMsg($"任务号{taskNo}开始执行绑定异常{ex.ToString()}");
            }
            
            //warehousingAfterService.EmsInputEMSAbnormalTask(Param.EmsLocId);

            //var finishResult = warehousingAfterService.EmsInputFinishTask(productCode, Param.EmsLocId, taskNo, taskId);
            //this.StepMsg($"任务{taskNo},176,返回finishResult,{finishResult.ToJson()}");

            //if (finishResult > 0 || task?.TaskType == (int)EnumTaskType.Abnormal)
            //{
            //    Cache.TaskNo = taskNo;
            //}


        }
        // 获取条码
        //var productCode = Data.ProductCode;
        var productCode = taskService.GetPoductCodeByTaskNo(taskNo);
        if (string.IsNullOrWhiteSpace(productCode))
        {
            this.StepMsg($"条码为空.");

            return result;
        }
        if (productCode.StartsWith(ConstFields.NoRead))
        {
            productCode = ConstFields.NoRead;
        }
        if (productCode == ConstFields.NoRead || productCode == ConstFields.Default)
        {
            this.StepMsg($"{productCode}条码不存在.");
            return result;
        }



        this.StepMsg($"入库库位{Param.EmsLocId}|" +
            $"创建任务参数(TaskNo):{Data.RWorkNo}, 胎胚条码:{productCode}");


        // 获取任务
        //var taskService = K8.RSF.Client.Create<ITaskService>();
        //var task = taskService.GetTaskBeanByProductCode(productCode);
        var task = taskService.GetEmsTaskBeanByTaskNo(taskNo, Param.EmsLocId);
        //this.StepMsg($"条码{productCode}, taskbean222{task.ToJson()}");
        this.StepMsg($"胎胚条码:{productCode}查找任务完成");
        if (task is null)
        {
            this.StepMsg($"ErrorNo：{productCode}, 任务未找到");
            return result;
        }
        //if (task.TaskType == (int)EnumTaskType.Abnormal) 
        //{
        //    this.StepMsg($"ErrorNo：{productCode},已创建异常任务");
        //    return result;
        //}

        if (task is not null && task.PairWait == 0) // 不是配对完成
        {
            this.StepMsg($"任务{taskNo},164");

            this.StepMsg($"任务{taskNo},166");
            var taskId = task?.Id ?? 0;
            this.StepMsg($"任务{taskNo},168");
            var remark = task?.Remark;





            var finishResult = warehousingAfterService.EmsInputFinishTask(productCode, Param.EmsLocId, taskNo, taskId);
            this.StepMsg($"任务{taskNo},176,返回finishResult,{finishResult.ToJson()}");
            // 修改状态
            //taskService.UpdateTaskCmdStatus(Param.LocId, task?.Id ?? 0, (int)EnumTaskCmdStatus.Finish);

            //var num = taskService.BakAndDeleteCmdByTaskId(task?.Id ?? 0);

            //this.StepMsg($"{Value.ProductCode}任务绑定返回值：{num}.");

            //var positionService = K8.RSF.Client.Create<IPositionService>();
            //// 修改货位TaskId
            //positionService.UpdateRcsLocationIsProductCode(Param.LocId, Value.ProductCode, true);
            if (finishResult > 0 || task?.TaskType == (int)EnumTaskType.Abnormal)
            {
                Cache.TaskNo = taskNo;
            }
        }
        //Cache.TaskNo = taskNo;
        this.StepMsg($"流水号:{taskNo}已执行");
        return result;

    }

}
